<template>
  <div>

    <!-- 新增电影的大表单 -->
    <el-form 
      ref="form" :model="form" :rules="rules"
      label-width="100px" style="width:500px;">
      <el-form-item label="封面图片" prop="cover">
        <el-upload
          class="avatar-uploader"
          :action="`${UPLOADURL}/upload`"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :before-upload="beforeUpload">
          <img 
            v-if="form.cover" 
            :src="form.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      
      <el-form-item label="电影分类">
        <el-radio v-model="form.categoryId" label="1">热映</el-radio>
        <el-radio v-model="form.categoryId" label="2">待映</el-radio>
        <el-radio v-model="form.categoryId" label="3">经典</el-radio>
      </el-form-item>

      <el-form-item label="电影名称" prop="title">
        <el-input placeholder="请输入电影名称" v-model="form.title"/>
      </el-form-item>

      <el-form-item label="电影类型" prop="type">
        <el-select style="width:100%;" v-model="form.type" multiple placeholder="请选择">
          <el-option 
            v-for="item in types" :key="item.id" 
            :value="item.typename">
          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="电影主演" prop="starActor">
        <el-select
          style="width:100%;"
          v-model="form.starActor"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading">
          <el-option
            v-for="item in actors"
            :key="item.id"
            :value="item.actor_name">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="上映时间" prop="showingon">
        <el-date-picker
          v-model="form.showingon"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="电影评分" prop="score">
        <el-input placeholder="请输入评分" v-model="form.score"/>
      </el-form-item>

      <el-form-item label="电影时长" prop="duration">
        <el-input placeholder="请输入电影时长" v-model="form.duration"/>
      </el-form-item>

      <el-form-item label="电影简介" prop="description">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请输入简介内容"
          v-model="form.description">
        </el-input>      
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
    
  </div>
</template>

<script>
import httpApi from '@/http';
export default {
  data() {
    return {

      loading: false, // 描述当前列表是否正在加载中
      actors: [],     // 保存模糊查询演员列表后的结果

      types: [],      // 存储所有的电影类型 
      form: {
        categoryId: '1',
        cover: '',
        title: '',
        type: [],
        starActor: [],
        showingon: '',
        score: '',
        description: '',
        duration: ''
      },
      rules: {
        cover: [{required:true, message:'必填项', trigger: 'blur'}],
        title: [{required:true, message:'必填项', trigger: 'blur'}],
        type: [{required:true, message:'必填项', trigger: 'change'}],
        starActor: [{required:true, message:'必填项', trigger: 'change'}],
        showingon: [{required:true, message:'必填项', trigger: 'blur'}],
        score: [{required:true, message:'必填项', trigger: 'blur'}],
        description: [{required:true, message:'必填项', trigger: 'blur'}],
        duration: [{required:true, message:'必填项', trigger: 'blur'}],
      }
    }
  },
  methods: {

    /** 提交表单 */
    onSubmit(){
      this.$refs['form'].validate(valid=>{
        if(valid){
          // 使用中文斜杠，将数组元素拼接成字符串，才可以发给服务端
          this.form.starActor = this.form.starActor.join('／')
          this.form.type = this.form.type.join('／')
          console.log(this.form)
          // 发送请求，提交数据
          httpApi.MovieApi.add(this.form).then(res=>{
            console.log('添加成功', res)
            if(res.data.code==200){
              this.$message({
                message:'恭喜您，电影新增成功', 
                type:'success'
              })
              // 跳转到电影列表页：/home/movie-list
              this.$router.push('/home/movie-list')
            }
          })
        }
      })
    },

    /** 通过姓名关键字异步加载演员列表，加载到结果后，显示在列表项中*/
    remoteMethod(query){
      this.loading = true;  // 告诉下拉框，数据正在加载中
      // 发送请求，加载演员列表
      httpApi.ActorApi
        .queryActorsByNameLike({name:query}).then(res=>{
          this.loading = false;
          console.log('模糊查询结果', res)
          // 将数据存入data，在页面中显示
          this.actors = res.data.data
      })
    },

    // 处理上传成功后的业务
    uploadSuccess(res, file) {
      console.log(res)
      // 将上传成功后的图片访问路径，存入form对象
      this.form.cover = res.data
    },

    // 处理上传之前的格式大小验证
    beforeUpload(file) {
      const isJPG = 
        file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG|PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  },

  /** 生命周期，挂载完毕后执行 */
  mounted(){
    // 加载所有的电影类型
    httpApi.MovieApi.queryAllTypes().then(res=>{
      console.log('加载所有电影类型', res)
      // 保存起来，在页面中遍历显示el-option
      this.types = res.data.data
    })
  }
};
</script>

<style lang="scss" scoped></style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    display: block;
  }
</style>
